package com.cms.controller.admin;

import com.cms.domain.Feedback;
import com.cms.entity.Div;
import com.cms.service.DivService;
import com.cms.utils.TableUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;


/**
 * Controller - 表单
 * 
 * 
 * 
 */
@Controller("adminDivController")
@RequestMapping("/admin/div")
public class DivController extends BaseController {

	@Autowired
	private DivService divService;

	/**
     * 列表
     */
	@RequestMapping
    public String index(Integer pageNumber, ModelMap modelMap){
    	setListQuery();
		if(pageNumber==null){
			pageNumber = 1;
		}
		modelMap.addAttribute("page", divService.findPage(pageNumber,PAGE_SIZE));
        return getView("div/index");
    }
    
	/**
	 * 添加
	 */
	@RequestMapping("/add")
	public String add() {
		return getView("div/add");
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	public String save(Div div) {
		div.setCreateDate(LocalDateTime.now());
		div.setUpdateDate(LocalDateTime.now());
		divService.save(div);
		//创建数据库表
		TableUtils.create(div.getTableName());
		return "redirect:"+getListQuery("/admin/div");
	}

	/**
	 * 编辑
	 */
	@RequestMapping("/edit")
	public String edit(Integer id, ModelMap modelMap) {
		Div div = divService.getById(id);
		modelMap.addAttribute("div", div);
		return getView("div/edit");
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	public String update(Div div) {
		div.setUpdateDate(LocalDateTime.now());
		divService.updateById(div);
		return "redirect:"+getListQuery("/admin/div");
	}

	/**
	 * 删除
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Feedback delete(Integer[] ids) {
		if(ArrayUtils.isNotEmpty(ids)){
			for(Integer id:ids){
				Div div = divService.getById(id);
				TableUtils.delete(div.getTableName());
				divService.removeById(id);
			}
		}
		return Feedback.success(new HashMap<>());
	}

}